import axios from 'axios'
import { Notification } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import qs from 'qs'

// create an axios instance 创建axios请求对象
const service = axios.create({
  baseURL: process.env.VUE_APP_REAL_API, // url = base url + request url
  transformRequest: [function(data) {
    // 对 data 进行任意转换处理
    return qs.stringify(data)
  }],
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor 请求拦截
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // 请求错误处理
    const err = error.toString().split(':')[1]
    if (err.includes('Network Error')) {
      console.error('请求出现错误！原因：网络错误!' + err)
      Notification.error({
        title: '网络错误!',
        message: err,
        dangerouslyUseHTMLString: true,
        duration: 5 * 1000
      })
      return Promise.reject()
    } else if (err.includes(' timeout')) {
      console.error('请求出现错误！原因：请求超时!' + err)
      Notification.error({
        title: '请求超时!',
        message: err,
        dangerouslyUseHTMLString: true,
        duration: 5 * 1000
      })
      return Promise.reject()
    } else {
      console.log(error) // for debug
      return Promise.reject(error)
    }
  }
)

// response interceptor 响应拦截
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log(response)
    const res = response.data
    // 处理文件下载
    if (res.type === 'application/octet-stream') {
      console.log(res.type)
      return response
    }

    // 如果自定义代码不是200，则判断为错误.
    // 508: 非法令牌; 512: 其他客户登录; 514: 令牌过期;
    if (res.code === 508 || res.code === 512 || res.code === 514) {
      // to re-login
      Notification.error({
        title: '错误',
        message: res.msg || '登录异常！',
        duration: 5 * 1000
      })
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    } else if (res.code === 401) {
      router.push('/401')
    } else if (res.code !== 200) {
      Notification.error({
        title: '错误',
        message: res.msg || '服务器错误！',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || '服务器错误！'))
    } else {
      return res
    }
  },
  // 错误处理
  error => {
    const err = error.toString().split(':')[1]
    if (err.includes('Network Error')) {
      console.error('请求出现错误！原因：网络错误!' + err)
      Notification.error({
        title: '网络错误!',
        message: err,
        dangerouslyUseHTMLString: true,
        duration: 5 * 1000
      })
      return Promise.reject()
    } else if (err.includes(' timeout')) {
      console.error('请求出现错误！原因：请求超时!' + err)
      Notification.error({
        title: '请求超时!',
        message: err,
        dangerouslyUseHTMLString: true,
        duration: 5 * 1000
      })
      return Promise.reject()
    } else {
      console.log('请求出现错误！原因：' + err)
      Notification.error({
        title: '未知异常!',
        message: error || '服务器错误！',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }
)

export default service
